import axios from 'axios'
import { config } from '@/config'

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  timeout: config.API_TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('Ticket Tracking API Error:', error)
    if (error.code === 'ERR_NETWORK' || error.code === 'ERR_CONNECTION_REFUSED') {
      const fallbackError = new Error('BACKEND_UNAVAILABLE')
      fallbackError.isFallback = true
      return Promise.reject(fallbackError)
    }
    return Promise.reject(error)
  }
)

/**
 * 工单状态跟踪API
 */
export const ticketTrackingApi = {
  /**
   * 获取工单的状态跟踪历史
   */
  getTicketTrackingHistory(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking`)
  },

  /**
   * 分页获取工单的状态跟踪历史
   */
  getTicketTrackingHistoryPage(ticketId, params = {}) {
    return apiClient.get(`/tickets/${ticketId}/tracking/page`, { params })
  },

  /**
   * 获取工单的状态变更历史
   */
  getStatusChangeHistory(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/status-changes`)
  },

  /**
   * 获取工单的分配历史
   */
  getAssignmentHistory(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/assignments`)
  },

  /**
   * 获取用户可见的跟踪记录
   */
  getVisibleTrackingHistory(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/visible`)
  },

  /**
   * 获取工单的最后一次操作
   */
  getLastOperation(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/last-operation`)
  },

  /**
   * 获取工单的最后一次状态变更
   */
  getLastStatusChange(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/last-status-change`)
  },

  /**
   * 获取操作人的操作记录
   */
  getOperatorHistory(operatorId, params = {}) {
    return apiClient.get(`/tickets/tracking/operator/${operatorId}`, { params })
  },

  /**
   * 获取时间范围内的跟踪记录
   */
  getTrackingHistoryByTimeRange(startTime, endTime, params = {}) {
    return apiClient.get('/tickets/tracking/time-range', {
      params: {
        startTime: startTime.toISOString(),
        endTime: endTime.toISOString(),
        ...params
      }
    })
  },

  /**
   * 获取工单操作统计
   */
  getTicketOperationStats(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/stats`)
  },

  /**
   * 获取操作人统计
   */
  getOperatorStats(operatorId) {
    return apiClient.get(`/tickets/tracking/operator/${operatorId}/stats`)
  },

  /**
   * 获取工单操作次数
   */
  getOperationCount(ticketId) {
    return apiClient.get(`/tickets/${ticketId}/tracking/count`)
  },

  /**
   * 获取特定类型操作次数
   */
  getOperationCountByType(ticketId, trackingType) {
    return apiClient.get(`/tickets/${ticketId}/tracking/count/${trackingType}`)
  },

  /**
   * 删除工单跟踪记录
   */
  deleteTicketTracking(ticketId) {
    return apiClient.delete(`/tickets/${ticketId}/tracking`)
  },

  /**
   * 清理过期跟踪记录
   */
  cleanupExpiredTracking(cutoffTime) {
    return apiClient.delete('/tickets/tracking/cleanup', {
      params: {
        cutoffTime: cutoffTime.toISOString()
      }
    })
  }
}

/**
 * 模拟数据（用于后端不可用时的降级处理）
 */
export const mockTicketTrackingApi = {
  getTicketTrackingHistory(ticketId) {
    return Promise.resolve({
      success: true,
      data: [
        {
          id: 1,
          ticketId: ticketId,
          trackingType: 'CREATED',
          oldValue: null,
          newValue: 'OPEN',
          fieldName: 'status',
          description: '工单已创建',
          operatorId: 1,
          operatorName: '系统管理员',
          operatorRole: 'ADMIN',
          isSystemOperation: false,
          isVisibleToCustomer: true,
          createdAt: new Date().toISOString()
        },
        {
          id: 2,
          ticketId: ticketId,
          trackingType: 'STATUS_CHANGED',
          oldValue: 'OPEN',
          newValue: 'IN_PROGRESS',
          fieldName: 'status',
          description: '工单状态变更为处理中',
          operatorId: 2,
          operatorName: '客服小王',
          operatorRole: 'AGENT',
          isSystemOperation: false,
          isVisibleToCustomer: true,
          createdAt: new Date(Date.now() - 3600000).toISOString()
        },
        {
          id: 3,
          ticketId: ticketId,
          trackingType: 'ASSIGNED',
          oldValue: null,
          newValue: '客服小王',
          fieldName: 'assignedTo',
          description: '工单已分配给客服小王',
          operatorId: 1,
          operatorName: '系统管理员',
          operatorRole: 'ADMIN',
          isSystemOperation: false,
          isVisibleToCustomer: true,
          createdAt: new Date(Date.now() - 7200000).toISOString()
        }
      ],
      message: '获取状态跟踪历史成功（模拟数据）'
    })
  },

  getStatusChangeHistory(ticketId) {
    return Promise.resolve({
      success: true,
      data: [
        {
          id: 2,
          ticketId: ticketId,
          trackingType: 'STATUS_CHANGED',
          oldValue: 'OPEN',
          newValue: 'IN_PROGRESS',
          fieldName: 'status',
          description: '工单状态变更为处理中',
          operatorId: 2,
          operatorName: '客服小王',
          operatorRole: 'AGENT',
          isSystemOperation: false,
          isVisibleToCustomer: true,
          createdAt: new Date(Date.now() - 3600000).toISOString()
        }
      ],
      message: '获取状态变更历史成功（模拟数据）'
    })
  },

  getAssignmentHistory(ticketId) {
    return Promise.resolve({
      success: true,
      data: [
        {
          id: 3,
          ticketId: ticketId,
          trackingType: 'ASSIGNED',
          oldValue: null,
          newValue: '客服小王',
          fieldName: 'assignedTo',
          description: '工单已分配给客服小王',
          operatorId: 1,
          operatorName: '系统管理员',
          operatorRole: 'ADMIN',
          isSystemOperation: false,
          isVisibleToCustomer: true,
          createdAt: new Date(Date.now() - 7200000).toISOString()
        }
      ],
      message: '获取分配历史成功（模拟数据）'
    })
  },

  getLastOperation(ticketId) {
    return Promise.resolve({
      success: true,
      data: {
        id: 2,
        ticketId: ticketId,
        trackingType: 'STATUS_CHANGED',
        oldValue: 'OPEN',
        newValue: 'IN_PROGRESS',
        fieldName: 'status',
        description: '工单状态变更为处理中',
        operatorId: 2,
        operatorName: '客服小王',
        operatorRole: 'AGENT',
        isSystemOperation: false,
        isVisibleToCustomer: true,
        createdAt: new Date(Date.now() - 3600000).toISOString()
      },
      message: '获取最后一次操作成功（模拟数据）'
    })
  },

  getOperationCount(ticketId) {
    return Promise.resolve({
      success: true,
      data: 3,
      message: '获取操作次数成功（模拟数据）'
    })
  }
}

export default ticketTrackingApi

